<template>
  <div class="flow-management">
    <div class="page-header">
      <h2>流程管理</h2>
      <el-button type="primary" @click="createFlow" :icon="Plus">新建流程</el-button>
    </div>
    
    <!-- 搜索筛选 -->
    <div class="search-section">
      <el-form :model="searchForm" inline>
        <el-form-item label="流程编码">
          <el-input v-model="searchForm.flowCode" placeholder="请输入流程编码" clearable></el-input>
        </el-form-item>
        <el-form-item label="流程名称">
          <el-input v-model="searchForm.flowName" placeholder="请输入流程名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
            <el-option label="数据处理" value="data"></el-option>
            <el-option label="业务流程" value="business"></el-option>
            <el-option label="系统集成" value="integration"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="草稿" value="0"></el-option>
            <el-option label="已发布" value="1"></el-option>
            <el-option label="已下线" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchFlows" :icon="Search">搜索</el-button>
          <el-button @click="resetSearch" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 流程列表 -->
    <div class="table-section">
      <el-table 
        :data="flowList" 
        v-loading="loading"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="flowCode" label="流程编码" width="150"></el-table-column>
        <el-table-column prop="flowName" label="流程名称" width="200"></el-table-column>
        <el-table-column prop="category" label="分类" width="120">
          <template #default="{ row }">
            <el-tag :type="getCategoryType(row.category)">
              {{ getCategoryLabel(row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="version" label="版本" width="100"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons-container">
              <el-button type="primary" size="small" @click="editFlow(row)" :icon="Edit">编辑</el-button>
              <el-button type="success" size="small" @click="designFlow(row)" :icon="Setting">设计</el-button>
              <el-button 
                size="small" 
                :type="row.status === 1 ? 'warning' : 'success'"
                @click="toggleStatus(row)"
              >
                {{ row.status === 1 ? '下线' : '发布' }}
              </el-button>
              <el-button type="primary" size="small" @click="copyFlow(row)" :icon="CopyDocument">复制</el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="deleteFlow(row)"
                :icon="Delete"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 新建/编辑流程对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form 
        :model="flowForm" 
        :rules="flowRules" 
        ref="flowFormRef"
        label-width="100px"
      >
        <el-form-item label="流程编码" prop="flowCode">
          <el-input 
            v-model="flowForm.flowCode" 
            placeholder="请输入流程编码"
            :disabled="isEdit"
          ></el-input>
        </el-form-item>
        <el-form-item label="流程名称" prop="flowName">
          <el-input v-model="flowForm.flowName" placeholder="请输入流程名称"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="flowForm.category" placeholder="请选择分类" style="width: 100%">
            <el-option label="数据处理" value="data"></el-option>
            <el-option label="业务流程" value="business"></el-option>
            <el-option label="系统集成" value="integration"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="版本" prop="version">
          <el-input v-model="flowForm.version" placeholder="请输入版本号"></el-input>
        </el-form-item>
        <el-form-item label="应用名称" prop="applicationName">
          <el-input v-model="flowForm.applicationName" placeholder="请输入应用名称"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="flowForm.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入流程描述"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveFlow" :loading="saving">
            {{ saving ? '保存中...' : '确定' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Search, Refresh, Edit, Setting, Delete, 
  CopyDocument 
} from '@element-plus/icons-vue'
import { getFlowPage, createFlow as createFlowApi, updateFlow, deleteFlow as deleteFlowApi, updateFlowStatus, copyFlow as copyFlowApi } from '@/api/flow'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const flowFormRef = ref(null)

// 搜索表单
const searchForm = reactive({
  flowCode: '',
  flowName: '',
  category: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 流程列表
const flowList = ref([])

// 流程表单
const flowForm = reactive({
  id: null,
  flowCode: '',
  flowName: '',
  category: '',
  version: '1.0.0',
  applicationName: '',
  description: ''
})

// 表单验证规则
const flowRules = {
  flowCode: [
    { required: true, message: '请输入流程编码', trigger: 'blur' },
    { pattern: /^[a-zA-Z][a-zA-Z0-9_-]*$/, message: '流程编码只能包含字母、数字、下划线和横线，且以字母开头', trigger: 'blur' }
  ],
  flowName: [
    { required: true, message: '请输入流程名称', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' },
    { pattern: /^\d+\.\d+\.\d+$/, message: '版本号格式应为 x.y.z', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑流程' : '新建流程')

/**
 * 获取分类标签
 */
const getCategoryLabel = (category) => {
  const labels = {
    data: '数据处理',
    business: '业务流程',
    integration: '系统集成'
  }
  return labels[category] || category
}

/**
 * 获取分类类型
 */
const getCategoryType = (category) => {
  const types = {
    data: 'primary',
    business: 'success',
    integration: 'warning'
  }
  return types[category] || ''
}

/**
 * 获取状态标签
 */
const getStatusLabel = (status) => {
  const labels = {
    0: '草稿',
    1: '已发布',
    2: '已下线'
  }
  return labels[status] || '未知'
}

/**
 * 获取状态类型
 */
const getStatusType = (status) => {
  const types = {
    0: 'info',
    1: 'success',
    2: 'warning'
  }
  return types[status] || ''
}

/**
 * 加载流程列表
 */
const loadFlowList = async () => {
  loading.value = true
  try {
    // 调用API获取流程列表
    const response = await getFlowPage({
      current: pagination.current,
      size: pagination.size,
      flowCode: searchForm.flowCode,
      flowName: searchForm.flowName,
      category: searchForm.category,
      status: searchForm.status
    })
    
    if (response.code === 200) {
      flowList.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error('加载流程列表失败：' + response.message)
    }
    
  } catch (error) {
    console.error('加载流程列表失败:', error)
    ElMessage.error('加载流程列表失败：' + (error.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

/**
 * 搜索流程
 */
const searchFlows = () => {
  pagination.current = 1
  loadFlowList()
}

/**
 * 重置搜索
 */
const resetSearch = () => {
  Object.assign(searchForm, {
    flowCode: '',
    flowName: '',
    category: '',
    status: ''
  })
  searchFlows()
}

/**
 * 分页大小变化
 */
const handleSizeChange = (size) => {
  pagination.size = size
  loadFlowList()
}

/**
 * 当前页变化
 */
const handleCurrentChange = (current) => {
  pagination.current = current
  loadFlowList()
}

/**
 * 新建流程
 */
const createFlow = () => {
  isEdit.value = false
  dialogVisible.value = true
}

/**
 * 编辑流程
 */
const editFlow = (row) => {
  isEdit.value = true
  Object.assign(flowForm, row)
  dialogVisible.value = true
}

/**
 * 设计流程
 */
const designFlow = (row) => {
  router.push(`/flow/designer/${row.id}`)
}

/**
 * 切换状态
 */
const toggleStatus = async (row) => {
  const action = row.status === 1 ? '下线' : '发布'
  const newStatus = row.status === 1 ? 2 : 1
  
  try {
    await ElMessageBox.confirm(
      `确定要${action}流程"${row.flowName}"吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用API切换状态
    const response = await updateFlowStatus(row.id, { status: newStatus })
    
    if (response.code === 200) {
      row.status = newStatus
      ElMessage.success(`${action}成功`)
    } else {
      ElMessage.error(`${action}失败：` + response.message)
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('切换状态失败:', error)
      ElMessage.error(`${action}失败：` + (error.message || '网络错误'))
    }
  }
}

/**
 * 复制流程
 */
const copyFlow = async (row) => {
  try {
    const { value: newFlowCode } = await ElMessageBox.prompt(
      '请输入新流程编码',
      '复制流程',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[a-zA-Z][a-zA-Z0-9_-]*$/,
        inputErrorMessage: '流程编码只能包含字母、数字、下划线和横线，且以字母开头'
      }
    )
    
    // 调用API复制流程
    const response = await copyFlowApi(row.id, { newFlowCode })
    
    if (response.code === 200) {
      ElMessage.success('复制成功')
      loadFlowList()
    } else {
      ElMessage.error('复制失败：' + response.message)
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('复制失败：' + (error.message || '网络错误'))
    }
  }
}

/**
 * 删除流程
 */
const deleteFlow = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除流程"${row.flowName}"吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用API删除流程
    const response = await deleteFlowApi(row.id)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadFlowList()
    } else {
      ElMessage.error('删除失败：' + response.message)
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除流程失败:', error)
      ElMessage.error('删除失败：' + (error.message || '网络错误'))
    }
  }
}

/**
 * 保存流程
 */
const saveFlow = async () => {
  if (!flowFormRef.value) return
  
  try {
    await flowFormRef.value.validate()
    saving.value = true
    
    let response
    // 调用API保存流程
    if (isEdit.value) {
      response = await updateFlow(flowForm.id, flowForm)
    } else {
      response = await createFlowApi(flowForm)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      loadFlowList()
    } else {
      ElMessage.error('保存失败：' + response.message)
    }
    
  } catch (error) {
    console.error('保存流程失败:', error)
    if (error.message) {
      ElMessage.error('保存失败：' + (error.message || '网络错误'))
    }
  } finally {
    saving.value = false
  }
}

/**
 * 重置表单
 */
const resetForm = () => {
  if (flowFormRef.value) {
    flowFormRef.value.resetFields()
  }
  Object.assign(flowForm, {
    id: null,
    flowCode: '',
    flowName: '',
    category: '',
    version: '1.0.0',
    applicationName: '',
    description: ''
  })
}

// 生命周期
onMounted(() => {
  loadFlowList()
})
</script>

<style scoped>
.flow-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-section {
  margin-top: 20px;
  text-align: right;
}

/* 操作按钮容器样式 */
.action-buttons-container {
  display: flex;
  flex-wrap: wrap;
  gap: 6px 8px;
  align-items: center;
  justify-content: flex-start;
  line-height: 1.2;
}

/* 操作按钮样式优化 */
:deep(.el-button--small) {
  padding: 5px 12px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
  margin: 0;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #409eff, #3a8ee6);
  border: none;
}

:deep(.el-button--success) {
  background: linear-gradient(135deg, #67c23a, #5daf34);
  border: none;
}

:deep(.el-button--danger) {
  background: linear-gradient(135deg, #f56c6c, #f25c5c);
  border: none;
}

:deep(.el-button--warning) {
  background: linear-gradient(135deg, #e6a23c, #d19e2a);
  border: none;
}

.dialog-footer {
  text-align: right;
}
</style>